package com.woniuxy.health.medical.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.health.aspect.OperationLogAnnotation;
import com.woniuxy.health.dto.OrderDto;
import com.woniuxy.health.medical.service.IInquiryAppointmentService;
import com.woniuxy.health.vo.OrderDetailVO;
import com.woniuxy.health.vo.OrderDetailVO2;
import com.woniuxy.health.vo.UploadDoctorAnswerVO;
import com.woniuxy.health.vo.ViewDetailsVO;
import com.woniuxy.utils.result.Result;
import lombok.SneakyThrows;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.woniuxy.health.medical.service.IOrderDetailService;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author woniuxy
 * @since 2023-09-04
 */
@RestController
@RequestMapping("/order-detail")
public class OrderDetailController {

    private final IOrderDetailService orderDetailServiceImpl;
    private final RedisTemplate redisTemplate;
    private final IInquiryAppointmentService iInquiryAppointmentService;

    @Autowired
    public OrderDetailController(IOrderDetailService orderDetailServiceImpl, RedisTemplate redisTemplate, IInquiryAppointmentService iInquiryAppointmentService){
        this.orderDetailServiceImpl = orderDetailServiceImpl;
        this.redisTemplate = redisTemplate;
        this.iInquiryAppointmentService = iInquiryAppointmentService;
    }


    //体检订单/挂号订单 tjy
    //批量导出
    @OperationLogAnnotation(module = "订单列表", type = "导出", description = "导出订单Excel")
    @PostMapping("/download")
    public Result download(HttpServletResponse resp) throws IOException {

        // rawFileName 设置excel文件名
        setExcelRespProp(resp, "全部数据");

        List<OrderDetailVO2> orderDetailVO2s = orderDetailServiceImpl.getAll();

        EasyExcel.write(resp.getOutputStream())
                .head(OrderDetailVO2.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("订单列表")
                .doWrite(orderDetailVO2s);

        return Result.ok();
    }

    public static void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        // 设置ContentType,通知页面返回的数据格式是一个excel文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8")
                .replaceAll("\\+", "%20");
        response.setHeader("Content-disposition",
                "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }






    //无条件查询全部(导出)


    //条件分页查询 (订单编号,状态,科室,就诊日期) // 高级查询
    @PostMapping("/findOrderPage/{pageNum}/{pageSize}")
    public Result findOrderPage(@RequestBody OrderDto orderDto,
                                @PathVariable("pageNum") Integer pageNum,
                                @PathVariable("pageSize")Integer pageSize) {

        Page<Object> page = Page.of(pageNum, pageSize);

        Page orderVoPage = orderDetailServiceImpl.getOrderPage(page,orderDto);

        return Result.ok(orderVoPage);
    }

    //查询订单详情
    @GetMapping("/searchOrderDetailById/{id}")
    public Result searchOrderDetailById(@PathVariable Long id) {

        OrderDetailVO2 orderDetailVO2 = orderDetailServiceImpl.searchOrderDetailById(id);

        return Result.ok(orderDetailVO2);

    }

    //根据订单id,从redis中获取对应的病历详情和医生回复
    @GetMapping("/getDoctorAnswer")
    public Result getDiseaseDescription(Integer orderId){
        String doctorAnswer =
                (String) redisTemplate.opsForHash().get("DoctorAnswer", ""+orderId);

        String  diseaseDescription =
                (String) redisTemplate.opsForHash().get("DiseaseDescription", ""+orderId);

        return Result.ok(new ViewDetailsVO(doctorAnswer,diseaseDescription));
    }

    //写一个方法，医生提交回复时，把回复内容放入redis数据库
    //前端可以获取到订单id,我们用订单id作为key
    @PostMapping("/upLoadDoctorAnswer")
    public Result upLoadDoctorAnswer(@RequestBody UploadDoctorAnswerVO uploadDoctorAnswerVO){

        //1、把医生的回复内容放入redis数据库中
        Integer orderId = uploadDoctorAnswerVO.getOrderId();
        String doctorAnswer = uploadDoctorAnswerVO.getDoctorAnswer();
        redisTemplate.opsForHash().put("DoctorAnswer",""+orderId, doctorAnswer);

        //2、在问诊预约表中,把医生回复的时间加上
        iInquiryAppointmentService.addReceptionTime(orderId);

        return Result.ok();
    }

    //写一个方法，用postman模拟客户端提交病情描述，然后把病情描述放入redis数据库
    @PostMapping("/upLoadDiseaseDescription")
    public Result upLoadDiseaseDescription(Integer orderId,
                                           String diseaseDescription){
        redisTemplate.opsForHash().put("DiseaseDescription",""+orderId, diseaseDescription);

        return Result.ok();
    }

    //联合订单表，问诊预约表，用户表进行查询问诊订单，并把数据放入VO对象返回
    @GetMapping("/getOrderList")
    public Result getOrderList(Integer pageNum,Integer pageSize){

        List<OrderDetailVO> list = orderDetailServiceImpl.getOrderList();
        System.out.println("查看list = " + list);

        return Result.ok(list);
    }


    //带条件的查询订单
    @GetMapping("/getOrderListByCondition")
    public Result getOrderListByCondition(Long id,
                                          Integer orderType,
                                          Integer orderState,
                                          String startDate,
                                          String endDate,
                                          Integer pageNum,
                                          Integer pageSize){

        Page page = Page.of(pageNum,pageSize);

        System.out.println("打印参数："+orderType+orderState+startDate+endDate);


        if(startDate !=null & endDate != null){
            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            // 将字符串转换为LocalDateTime对象
            LocalDateTime star = LocalDateTime.parse(startDate, formatter);
            LocalDateTime end = LocalDateTime.parse(endDate, formatter);


            Page<OrderDetailVO> voPage =
                    orderDetailServiceImpl.getOrderDetailByCondition(id, orderType, orderState, star, end, page);

            return Result.ok(voPage);

        }

        LocalDateTime star = null;
        LocalDateTime end = null;
        Page<OrderDetailVO> voPage =
                orderDetailServiceImpl.getOrderDetailByCondition(id, orderType, orderState, star, end, page);

        System.out.println("打印分页voPage = " + voPage);
        return Result.ok(voPage);

    }


}
